package com.vito.base.authoriza.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vito.base.authoriza.dao.DeptMapper;
import com.vito.base.authoriza.dao.SectionMapper;
import com.vito.base.authoriza.dao.UserMapper;
import com.vito.base.authoriza.model.DeptModel;
import com.vito.base.authoriza.service.DeptService;
import com.vito.base.exception.ParamErrorException;
import com.vito.base.factory.IDFactory;
import com.vito.base.model.DataGrid;
import com.vito.base.model.ResMsg;
import com.vito.base.model.Result;
import com.vito.base.tool.BaseTools;
import com.vito.base.util.Contants;
import com.vito.base.util.Validata;
import com.vito.dcs.section.model.SectionModel;
import com.vito.mq.ytx.YtxConstant;

@Service
public class DeptServiceImpl implements DeptService {
	private static final Logger log = LoggerFactory.getLogger(DeptServiceImpl.class);
	@Autowired
	private DeptMapper deptMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private com.vito.base.msg.service.MsgYtxService msgYtxService;
	@Autowired
	private SectionMapper sectionMapper;
	
	@Override
	public DataGrid<DeptModel> queryDeptByPage(Map<String,Object> param) {
		DataGrid<DeptModel> dg = new DataGrid<DeptModel>();
		Integer currentUserType = null;
		if(param.containsKey("currentUserType")){
			currentUserType = (Integer)param.get("currentUserType");
		}
		//判断是否为超级管理员或者管理员用户 其可以管理所有部门没有限制
		if(currentUserType!=null&&(currentUserType.equals(Contants.SUPER_USER_TYPE)||currentUserType.equals(Contants.ADMIN_USER_TYPE))){
			dg.setRows(deptMapper.querySuperUserDeptByPage(param));
			dg.setTotal(deptMapper.querySuperUserDeptByPageCount(param));
		}else{
			dg.setRows(deptMapper.queryDeptByPage(param));
			dg.setTotal(deptMapper.queryDeptCountByPage(param));
		}
		return dg;
	}

	@Override
	public List<DeptModel> queryDeptTree(DeptModel dept) {
		if(dept==null||dept.getDeptId()==null||"".equals(dept.getDeptId())){
			return null;
		}
		return deptMapper.queryDeptTree(dept);
	}

	@Override
	public List<DeptModel> queryTreeAll(Map<String,Object> dept) {
		Integer currentUserType = null;
		if(dept.containsKey("currentUserType")){
			currentUserType = (Integer)dept.get("currentUserType");
		}
		if(dept.containsKey("id")&&dept.get("id")!=null){
			dept.put("deptCode", deptMapper.queryDeptCodeById(dept.get("id").toString()));
		}
		
		//判断是否为超级管理员或者管理员用户 其可以管理所有部门没有限制
		if(currentUserType!=null&&(currentUserType.equals(Contants.SUPER_USER_TYPE)||currentUserType.equals(Contants.ADMIN_USER_TYPE))){
			return deptMapper.queryTreeSuperAll(dept);
		}else{
			return deptMapper.queryTreeAll(dept);
		}
		
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void saveDept(DeptModel dept) throws Exception {
		
		/*
		 *	 * @param pId 		 pid值
			 * @param tabName    表名
			 * @param tabPidCol	 pid字段名
			 * @param tabCodeCol code字段名
			 * @param tabIdCol	 id字段名 
		 * */
		
		if("2".equals(dept.getBase_name())){
			
			String des = dept.getDes();
			List parse = (List) JSONArray.parse(des);
			
			SectionModel secModel = new SectionModel();
			secModel.setSectionId(dept.getDeptParent());
			/**
			 * 拿到所有的Id，和查询的比对
			 */
			List<SectionModel> queryWorkArea = sectionMapper.queryWorkArea(secModel );
			
			String[] store = null;
			if(queryWorkArea != null && queryWorkArea.size() > 0){
				store = new String[queryWorkArea.size()];
				for (int i = 0; i < queryWorkArea.size(); i ++) {
					store[i] = queryWorkArea.get(i).getSectionId();
				}
			}
			String[] trans = null;
			if(parse != null && parse.size() > 0){
				trans = new String[parse.size()];
				for (int i = 0; i < parse.size(); i ++) {
					Map<String,String> m = (Map<String, String>) parse.get(i);
					if(!Validata.isNullOrEmpty(m.get("deptId"))){
						trans[i] = m.get("deptId");
					}
				}
			}
			List<String> newCK = new ArrayList<String>();
			if(store != null && store.length > 0){
				List<String> asList = Arrays.asList(store);
				List<String> asList2 = Arrays.asList(trans);
				for(int i = 0; i < asList.size(); i ++){
					if(!asList2.contains(asList.get(i))){
						newCK.add(asList.get(i));
					}
				}
				
			}
			
			/**
			 * 执行更新(逻辑删除)
			 */
			if(newCK.size() > 0){
				secModel.setTransList(newCK);
				sectionMapper.updateStatus(secModel);
			}
			
			for (Object object : parse) {
				Map<String,String> m = (Map<String, String>) object;
				if(Validata.isNullOrEmpty(m.get("deptId"))){
					String deptId = IDFactory.getIDFactory().getIdInc("TBL_BASE_DEPT")+"";
					dept.setOperTimer(new Date());
					String code = BaseTools.getBaseCodeByTab(dept.getDeptParent(), "TBL_BASE_DEPT", "DEPT_PARENT_ID", "DEPT_CODE", "DEPT_ID");
					if(dept.getDeptParent()==null||dept.getDeptParent().equals("")){
						dept.setDeptParent("0");
					}
					dept.setDeptCode(code);
					dept.setDeptId(deptId);
					dept.setDeptName(m.get("deptName"));
					dept.setDes(null);
					
					deptMapper.saveDept(dept);
					/**
					 * insert 子表
					 */
					SectionModel sectionModel = new SectionModel();
					String sec = IDFactory.getIDFactory().getIdInc("tbl_dcs_sys_work_area")+"";
					sectionModel.setId(sec);
					sectionModel.setSectionId(deptId);
					sectionModel.setUpdateUser(dept.getCurrentUser());
					sectionModel.setWorkAreaName(m.get("deptName"));
					sectionMapper.saveWorkArea(sectionModel);
				}else {
					/**
					 * 有id,走更新
					 */
					SectionModel sectionModel = new SectionModel();
					sectionModel.setSectionId(m.get("deptId"));
					sectionModel.setUpdateUser(dept.getCurrentUser());
					sectionModel.setWorkAreaName(m.get("deptName"));
					
					sectionMapper.updateDeptWhenWorkChange(sectionModel);
					sectionMapper.updateWorkArea(sectionModel);
				}
				
			}
		} else {
			dept.setOperTimer(new Date());
			String code = BaseTools.getBaseCodeByTab(dept.getDeptParent(), "TBL_BASE_DEPT", "DEPT_PARENT_ID", "DEPT_CODE", "DEPT_ID");
			if(dept.getDeptParent()==null||dept.getDeptParent().equals("")){
				dept.setDeptParent("0");
			}
			dept.setDeptCode(code);
			String deptId = IDFactory.getIDFactory().getIdInc("TBL_BASE_DEPT")+"";
			String area = dept.getArea();
			
			dept.setDeptId(deptId);
			dept.setArea(null);
			deptMapper.saveDept(dept);
			
			if("1".equals(dept.getBase_name())){
				SectionModel sectionModel = new SectionModel();
				String sec = IDFactory.getIDFactory().getIdInc("tbl_dcs_sys_section_ext")+"";
				sectionModel.setId(sec);
				sectionModel.setRoadWidth(area);
				sectionModel.setSectionId(deptId);
				sectionModel.setChargeName(dept.getContactsperson());
				sectionModel.setChargeTel(dept.getPhone());
				sectionModel.setPileLocation(dept.getAreaName());
				sectionModel.setUpdateUser(dept.getCurrentUser());
				sectionMapper.saveSection(sectionModel);
			} 
		}
		
		/*res.setCode(Result.CODE_OK);
		res.setMsg(ResMsg.SAVESUC);
		return res;*/
		//是否同步部门信息到容联
		/*if(YtxConstant.isSyncRlytx){
			msgYtxService.addGroup(dept.getDeptId(), dept.getDeptName(), YtxConstant.YTX_GROUP_LOCAL_TYPE_DEPT);
		}*/
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Result saveDept2(DeptModel dept) throws Exception {
		Result res = new Result();
		/*
		 *	 * @param pId 		 pid值
		 * @param tabName    表名
		 * @param tabPidCol	 pid字段名
		 * @param tabCodeCol code字段名
		 * @param tabIdCol	 id字段名 
		 * */
		
		if("2".equals(dept.getBase_name())){
			
			String des = dept.getDes();
			List parse = (List) JSONArray.parse(des);
			
			SectionModel secModel = new SectionModel();
			secModel.setSectionId(dept.getDeptParent());
			/**
			 * 拿到所有的Id，和查询的比对
			 */
			List<SectionModel> queryWorkArea = sectionMapper.queryWorkArea(secModel );
			
			String[] store = null;
			if(queryWorkArea != null && queryWorkArea.size() > 0){
				store = new String[queryWorkArea.size()];
				for (int i = 0; i < queryWorkArea.size(); i ++) {
					store[i] = queryWorkArea.get(i).getSectionId();
				}
			}
			String[] trans = null;
			if(parse != null && parse.size() > 0){
				trans = new String[parse.size()];
				for (int i = 0; i < parse.size(); i ++) {
					Map<String,String> m = (Map<String, String>) parse.get(i);
					if(!Validata.isNullOrEmpty(m.get("deptId"))){
						trans[i] = m.get("deptId");
					}
				}
			}
			List<String> newCK = new ArrayList<String>();
			if(store != null && store.length > 0){
				List<String> asList = Arrays.asList(store);
				List<String> asList2 = Arrays.asList(trans);
				for(int i = 0; i < asList.size(); i ++){
					if(!asList2.contains(asList.get(i))){
						newCK.add(asList.get(i));
					}
				}
				
			}
			
			/**
			 * 执行更新(逻辑删除)
			 */
			if(newCK.size() > 0){
				secModel.setTransList(newCK);
				int queryIsHaveVehicle = sectionMapper.queryIsHaveVehicle(secModel);
				if(queryIsHaveVehicle > 0){
					res.setCode(Result.CODE_PARA_ERROR);
					res.setMsg("所删除的工区下存在关联车辆，不允许删除");
					return res;
				}
				sectionMapper.updateStatus(secModel);
			}
			
			for (Object object : parse) {
				Map<String,String> m = (Map<String, String>) object;
				if(Validata.isNullOrEmpty(m.get("deptId"))){
					String deptId = IDFactory.getIDFactory().getIdInc("TBL_BASE_DEPT")+"";
					dept.setOperTimer(new Date());
					String code = BaseTools.getBaseCodeByTab(dept.getDeptParent(), "TBL_BASE_DEPT", "DEPT_PARENT_ID", "DEPT_CODE", "DEPT_ID");
					if(dept.getDeptParent()==null||dept.getDeptParent().equals("")){
						dept.setDeptParent("0");
					}
					dept.setDeptCode(code);
					dept.setDeptId(deptId);
					dept.setDeptName(m.get("deptName"));
					dept.setDes(null);
					
					deptMapper.saveDept(dept);
					/**
					 * insert 子表
					 */
					SectionModel sectionModel = new SectionModel();
					String sec = IDFactory.getIDFactory().getIdInc("tbl_dcs_sys_work_area")+"";
					sectionModel.setId(sec);
					sectionModel.setSectionId(deptId);
					sectionModel.setUpdateUser(dept.getCurrentUser());
					sectionModel.setWorkAreaName(m.get("deptName"));
					sectionMapper.saveWorkArea(sectionModel);
				}else {
					/**
					 * 有id,走更新
					 */
					SectionModel sectionModel = new SectionModel();
					sectionModel.setSectionId(m.get("deptId"));
					sectionModel.setUpdateUser(dept.getCurrentUser());
					sectionModel.setWorkAreaName(m.get("deptName"));
					
					sectionMapper.updateDeptWhenWorkChange(sectionModel);
					sectionMapper.updateWorkArea(sectionModel);
				}
				
			}
		} else {
			dept.setOperTimer(new Date());
			String code = BaseTools.getBaseCodeByTab(dept.getDeptParent(), "TBL_BASE_DEPT", "DEPT_PARENT_ID", "DEPT_CODE", "DEPT_ID");
			if(dept.getDeptParent()==null||dept.getDeptParent().equals("")){
				dept.setDeptParent("0");
			}
			dept.setDeptCode(code);
			String deptId = IDFactory.getIDFactory().getIdInc("TBL_BASE_DEPT")+"";
			String area = dept.getArea();
			
			dept.setDeptId(deptId);
			dept.setArea(null);
			deptMapper.saveDept(dept);
			
			if("1".equals(dept.getBase_name())){
				SectionModel sectionModel = new SectionModel();
				String sec = IDFactory.getIDFactory().getIdInc("tbl_dcs_sys_section_ext")+"";
				sectionModel.setId(sec);
				sectionModel.setRoadWidth(area);
				sectionModel.setSectionId(deptId);
				sectionModel.setChargeName(dept.getContactsperson());
				sectionModel.setChargeTel(dept.getPhone());
				sectionModel.setPileLocation(dept.getAreaName());
				sectionModel.setUpdateUser(dept.getCurrentUser());
				sectionMapper.saveSection(sectionModel);
			} 
		}
		
		res.setCode(Result.CODE_OK);
		res.setMsg(ResMsg.SAVESUC);
		return res;
		//是否同步部门信息到容联
		/*if(YtxConstant.isSyncRlytx){
			msgYtxService.addGroup(dept.getDeptId(), dept.getDeptName(), YtxConstant.YTX_GROUP_LOCAL_TYPE_DEPT);
		}*/
	}
	@Override
	public void deleteDept(DeptModel dept) throws ParamErrorException {
		//deptMapper.deleteDept(dept);
//		for(String check:dept.getCheckeds()){
//			List<Map<String, String>> list = userMapper.queryUserListDeptTree(check);
//			if(list!=null&&list.size()>1){
//				throw new ParamErrorException("部门下存在可用信息，暂时不能被禁用！");
//			}
//		}
		DeptModel deptModel = new DeptModel();
		for(String check:dept.getCheckeds()){
			//查询是否有子部门,如果有,则不能删除
			deptModel.setDeptId(check);
			deptModel.setDeptCode(deptMapper.queryDeptCodeById(check));
			List<Map<String, String>> list = deptMapper.queryDeptAndSubDeptByDept(deptModel);
			if(list!=null&&list.size()>1){
				throw new ParamErrorException("该部门下存在子部门，暂时不能被禁用！");
			}else{
				//查询是否有用户,如果有,则不能删除
				List<Map<String, String>> deptUserlist = deptMapper.queryDeptUserByDeptId(check);
				if(deptUserlist!=null&&deptUserlist.size()>0){
					throw new ParamErrorException("该部门下存在用户，暂时不能被禁用！");
				}
			}
		}
		
		dept.setOperTimer(new Date());
		deptMapper.updDisableDept(dept);
		//是否同步部门信息到容联
		if(YtxConstant.isSyncRlytx){
			msgYtxService.deleteGroup(dept.getDeptId(), YtxConstant.YTX_GROUP_LOCAL_TYPE_DEPT);
		}
	}
public static void main(String[] args) {
	
	List parse = (List) JSONArray.parse("[{\"deptName\":\"aa\",\"deptId\":\"\"},{\"deptName\":\"ss\",\"deptId\":\"\"},{\"deptName\":\"dd\",\"deptId\":\"\"}]");
	for (Object object : parse) {
		Map<String,String> m = (Map<String, String>) object;
		System.out.println(m.get("deptName")+"--->"+m.get("deptId"));
	}
	
}
	@Override
	public void updateDept(DeptModel dept) throws Exception {
		dept.setOperTimer(new Date());
		DeptModel deptModel = deptMapper.queryDeptById(new DeptModel(dept.getDeptId()));
		if(dept.getDeptParent()==null){
			dept.setDeptParent("0");
		}
		if(deptModel.getDeptParent()==null){
			deptModel.setDeptParent("0");
		}
		if(dept.getDeptParent().equals(deptModel.getDeptParent())){
			
			String area = dept.getArea();
			dept.setArea(null);
			deptMapper.updateDept(dept);
			
			if("1".equals(dept.getBase_name())){
				SectionModel sectionModel = new SectionModel();
				sectionModel.setSectionId(dept.getDeptId());
				sectionModel.setRoadWidth(area);
				sectionModel.setChargeName(dept.getContactsperson());
				sectionModel.setChargeTel(dept.getPhone());
				sectionModel.setPileLocation(dept.getAreaName());
				sectionModel.setUpdateUser(dept.getCurrentUser());
				
				sectionMapper.updateSection(sectionModel);
			}
			
		}else{
			
			dept.setDeptCode(deptModel.getDeptCode());
			if(deptMapper.checkParent(dept)>0){//当前父部门为子部门 需要更新父部门的pid
				//deptMapper.updateParentDeptPid(deptModel);
				//先修改被作为父的子节点 及其子节点的CODE
				String code = BaseTools.getBaseCodeByTab(deptModel.getDeptParent(), "TBL_BASE_DEPT", "DEPT_PARENT_ID", "DEPT_CODE", "DEPT_ID");
				
				DeptModel dm = deptMapper.queryDeptById(new DeptModel(dept.getDeptParent()));
				//处理被作为父 的节点及其子 
				dm.setDeptCodeNew(code);
				dm.setSessionDeptCode(dept.getSessionDeptCode());
				deptMapper.updateDeptLeafs(dm);	
				dm.setDeptParent(deptModel.getDeptParent());
				
				deptMapper.updateDept(dm);
				//处理原为父现在为子的节点
				String code2 = BaseTools.getBaseCodeByTab(dept.getDeptParent(), "TBL_BASE_DEPT", "DEPT_PARENT_ID", "DEPT_CODE", "DEPT_ID");
				 
				
				
				deptModel.setSessionDeptCode(dept.getSessionDeptCode());
				 
				deptModel.setDeptCodeNew(code2);
				deptMapper.updateDeptLeafs(deptModel);
				deptMapper.updateDept(dept);
				
				
				
			}else{
				String code = BaseTools.getBaseCodeByTab(dept.getDeptParent(), "TBL_BASE_DEPT", "DEPT_PARENT_ID", "DEPT_CODE", "DEPT_ID");
				deptModel.setDeptCodeNew(code); 
				deptModel.setSessionDeptCode(dept.getSessionDeptCode());
				deptMapper.updateDept(dept);
				deptMapper.updateDeptLeafs(deptModel);
			}
			
			


		}
		
/*		if(deptMapper.checkParent(dept)>0){//当前父部门为子部门 需要更新父部门的pid
			deptMapper.updateParentDeptPid(dept);
		}
		deptMapper.updateDept(dept);*/
		//是否同步部门信息到容联
		if(YtxConstant.isSyncRlytx){
			msgYtxService.updateGroup(dept.getDeptId(), dept.getDeptName(), YtxConstant.YTX_GROUP_LOCAL_TYPE_DEPT);
		}
	}

	@Override
	public List<DeptModel> queryDept(Map<String,Object> dept) {
		return deptMapper.queryDeptByPage(dept);
	}

	@Override
	public int saveDeptRole(DeptModel dept) {
		return deptMapper.saveDeptRole(dept);
	}

	@Override
	public DeptModel queryDeptById(DeptModel dept) {
		return deptMapper.queryDeptById(dept);
	}

	@Override
	public List<DeptModel> queryDeptByUserID(String userId) {
		return deptMapper.queryDeptByUserID(userId);
	}

	@Override
	public String queryDeptParentId(String deptCode) {
		String[] codes  = BaseTools.getParentCodeByCode(deptCode);
		DeptModel dept = new DeptModel();
		dept.setCheckeds(codes);
		return deptMapper.queryDeptParentId(dept);
	}

	@Override
	public String getDeptName(String deptId) {
		String deptName = "";
		if(!StringUtils.isEmpty(deptId)){
			DeptModel model = new DeptModel();
			model.setDeptId(deptId);
			DeptModel deptModel = deptMapper.queryDeptById(model);
			if(deptModel!=null){
				deptName = deptModel.getDeptName();
			}
		}
		return deptName;
	}

	@Override
	public List<DeptModel> getDeptByPId(String pid) {
		return deptMapper.getDeptByPId(pid);
	}

	@Override
	public List<DeptModel> findDeptTreeByUserId(Map<String, String> map) {
		return deptMapper.findDeptTreeByUserId(map);
	}

	@Override
	public List<DeptModel> getRootDept(String deptId) {
		return deptMapper.queryRootDept(deptId);
	}

	@Override
	public List<Map<String, String>> queryDeptTreeByRootDept(String rootDept) {
		return deptMapper.queryDeptTreeByRootDept(rootDept);
	}

	@Override
	public String queryDeptCodeById(String deptId) {
		// TODO Auto-generated method stub
		return deptMapper.queryDeptCodeById(deptId);
	}

}


